// permission.js,此文件在main.js中直接导入即可，这边的思路是仿照的element-admin
import router from './index'
import store from '../store'
import screenfull from 'screenfull'
import 'nprogress/nprogress.css' // progress bar style
import NProgress from '@/utils/nprogress' // progress bar
import { getToken, removeToken } from '@/utils/tools'

router.beforeEach(async (to, from, next) => {
  const token = getToken(process.env.VUE_APP_COOKIE_TOKEN)
  NProgress.start()
  // 如果已经处于登录状态，跳到登录页重定向到首页
  if (token) {

    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (!store.state.authorized) {
        try {
          // 因为setAccessRoutes返回一个promise，await可获取结果
          router.addRoutes(await store.dispatch('setAccessRoutes'))
          store.dispatch('setAllDict')
          next({ ...to, replace: true })
        } catch (e) {
          removeToken()
          next({ path: '/login' })
          NProgress.done()
        }
      } else {
        next()
        // 全屏参数判断该页面是否全屏
        if (!screenfull.isEnabled) return
        if (to.meta && to.meta.fullScreen) {
          screenfull.request().catch(() => null)
        } else {
          if (screenfull.isFullscreen) {
            screenfull.exit()
          }
        }
      }
    }

    // 未登录
  } else {
    // decodeURIComponent("%2Fsystem%2Frole")
    // "/system/role"
    // encodeURIComponent("/")
    // "%2F"
    next(to.path !== '/login' ? { path: '/login', query: { old: to.path } } : true)
  }
})

router.afterEach(() => {
  NProgress.done()
})